package main

import (
    "gouniapp/configs"
	"gouniapp/routers"
	"log"
	"net"
	"os/exec"
	"runtime"
	"time"
)

const (
	defaultPort    = "2222"
	maxRetries     = 20          // 最大重试次数
	retryInterval  = 500 * time.Millisecond // 重试间隔
	serverTimeout  = 3 * time.Second        // 服务器检测超时
)

func main() {
	configs.InitConfig() // 初始化配置
	port := getPort()
	launchBrowserAsync(port)
	startServer(port)
}

// 获取端口
func getPort() string {
	if port := configs.Config.GetString("server.port"); port != "" {
		return port
	}
	return defaultPort
}

// 启动浏览器，仅在 Windows 系统上有效
func launchBrowserAsync(port string) {
	if runtime.GOOS != "windows" {
		return
	}
	go func() {
		if !waitForServerReady(port) {
			log.Println("服务器未就绪，放弃打开浏览器")
			return
		}
		if err := exec.Command("cmd", "/c", "start", configs.MyURL).Start(); err != nil {
			log.Printf("打开浏览器失败: %v", err)
		}
	}()
}

// 检查启动是否就绪
func waitForServerReady(port string) bool {
	for i := 0; i < maxRetries; i++ {
		if isServerReady(port) {
			return true
		}
		time.Sleep(retryInterval)
	}
	return false
}

func isServerReady(port string) bool {
	conn, err := net.DialTimeout("tcp", net.JoinHostPort("localhost", port), serverTimeout)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}

// 启动服务
func startServer(port string) {
	router := routers.SetupRouter()
	if err := router.Run(":" + port); err != nil {
        log.Fatalf("启动服务器失败: %v", err)
    }
}

//打包windows： CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build
//无窗口模式：CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -H=windowsgui"
//平板电脑： CGO_ENABLED=0 GOARCH=arm64 GOOS=linux go build
//目标环境glibc_2.34 not found版本太低，需要静态链接编译：CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"'